package com.weixin.gong.example.apache.commons.beanutils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author weixin.gong
 * @date 17-5-10 下午2:31
 */
public class BeanToMapExample {

    //BeanUtils操作的类必须有public修饰符
    public static class Bean {
        private int value;

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }

    @Test
    public void beanToMap() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Bean bean = new Bean();
        bean.setValue(1);
        //BeanUtils.describe(bean) 将bean的字段值转为String
        System.out.println("BeanToMap with BeanUtils:" + BeanUtils.describe(bean));
        Assert.assertEquals(bean.getValue() + "", BeanUtils.describe(bean).get("value"));
        //PropertyUtils.describe(bean) 保留bean的字段值的类型
        System.out.println("BeanToMap with PropertyUtils:" + PropertyUtils.describe(bean));
        Assert.assertEquals(bean.getValue(), (int) ((Integer) (PropertyUtils.describe(bean).get("value"))));
    }

    @Test
    public void mapToMap() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //不能将map转换成map
        //describe方法就像名字字面意思一样,是返回的对象的描述信息,而并不是将对象转成map
        Map map = new HashMap();
        map.put("value", 1);
        System.out.println(BeanUtils.describe(map));
        System.out.println(PropertyUtils.describe(map));
    }
}
